import { defineComponent, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElSelect, ElOption, ElInputNumber, ElDatePicker } from 'element-plus'

import type { SpanMethodProps, DetailVOList } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'

import ProSaasTable from '~/components/ProSaasTable'
import styles from '../../index.module.scss'

export default defineComponent(function Demo() {
  const router = useRouter()
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const searchValue = ref('1')
  const searchNum = ref('5')
  const searchTime = ref('')
  const url = ref('police/AnalysAlarmLimit')
  const list = ref<DetailVOList[]>([])
  const completeStatus = (value: any) => {
    switch (value) {
      case 'lx':
        return '零线'
        break
      case 'hx':
        return '火线'
        break
      case 'a':
        return '单线A'
        break
      case 'b':
        return '单线B'
        break
      case 'c':
        return '单线C'
        break
    }
  }
  const columns: TableColumnProps<DetailVOList>[] = [
    {
      label: '回路开关',
      prop: 'loopNum',
      showOverflowTooltip: true
    },
    {
      label: '运行时间',
      prop: 'reportTime',
      showOverflowTooltip: true
    },
    {
      label: '接触器',
      prop: 'diState',
      showOverflowTooltip: true,
      render: (_, value) => {
        return <>{value === 0 ? '断开' : '闭合'}</>
      }
    },
    {
      label: '线路/相位',
      prop: 'phase',
      showOverflowTooltip: true,
      render: (_, value) => {
        return <>{completeStatus(value)}</>
      }
    },
    {
      label: '电压(V)',
      prop: 'voltage',
      showOverflowTooltip: true
    },
    {
      label: '电流(A)',
      prop: 'current',
      showOverflowTooltip: true
    },
    {
      label: '有功功率(kW)',
      prop: 'activePower',
      showOverflowTooltip: true
    },
    {
      label: '功率因数',
      prop: 'powerFactor',
      showOverflowTooltip: true
    },
    {
      label: '漏电(A)',
      prop: 'leakageValue',
      showOverflowTooltip: true
    }
  ]

  //  合并单元格
  const spanMethod = ({
    row,
    // column,
    rowIndex,
    columnIndex
  }: SpanMethodProps) => {
    if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 8) {
      if (rowIndex % row.index === 0) {
        return {
          rowspan: row.index,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    } else {
      return {
        rowspan: 1,
        colspan: 1
      }
    }
  }

  //  筛选切换
  const searchChange = (value: any) => {
    if (value === '1') {
      searchTime.value = ''
      searchNum.value = '5'
      url.value = 'police/AnalysAlarmLimit'
      init()
    } else {
      searchNum.value = ''
      url.value = 'police/AnalysAlarmDate'
    }
  }
  const init = async () => {
    const { id } = router.currentRoute.value.query
    const params = {
      alarmInfoId: id,
      num: searchNum.value,
      beginTime: searchTime.value[0],
      endTime: searchTime.value[1],
      current: 1,
      size: 1000
    }
    const array: Array<DetailVOList> = []
    const { code, data } = await store.dispatch(url.value, params)
    if (code === 200) {
      if (data.records.length > 0) {
        data.records.forEach((item: any) => {
          item.detailVOList.forEach((row: any) => {
            array.push({
              index: item.detailVOList.length,
              loopNum: item.loopNum,
              reportTime: item.reportTime,
              diState: item.diState,
              leakageValue: item.leakageValue,
              phase: row.phase,
              voltage: row.voltage,
              current: row.current,
              activePower: row.activePower,
              powerFactor: row.powerFactor
            })
          })
        })
      }
      list.value = array
    }
  }
  // 按回车搜索列表
  // const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
  //   if ((evt as KeyboardEvent).key === 'Enter') init()
  // }
  onMounted(() => {
    init()
  })

  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          init()
        }, 100)
      }
    }
    return (
      <div>
        <div class={styles.search}>
          <div class={styles.search_left}>
            <ElSelect v-model={searchValue.value} onChange={searchChange}>
              <ElOption key="1" label={'报警前后运行数据'} value="1" />
              <ElOption key="2" label={'运行时间'} value="2" />
            </ElSelect>
          </div>
          <div class={styles.search_right}>
            {searchValue.value === '1' ? (
              <ElInputNumber
                v-model={searchNum.value}
                placeholder="输入数字 回车搜索"
                onChange={init}
                min={1}
                max={100}
                controls-position="right"
              />
            ) : (
              <ElDatePicker
                v-model={searchTime.value}
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="daterange"
                clearable={false}
                {...props}
              />
            )}
          </div>
        </div>
        <ProSaasTable<DetailVOList>
          ref={proSaasTableRef}
          columns={columns}
          data={list.value}
          spanMethod={spanMethod}
          needPagination={false}
        />
      </div>
    )
  }
})
